package com.test.tool.demo.websocket;

import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.messaging.handler.annotation.MessageExceptionHandler;
import org.springframework.messaging.simp.annotation.SendToUser;
import org.springframework.web.bind.annotation.*;

/**
 * 长连接发消息控制器
 *
 * @author 小八
 * @date 2022年04月25日15:48
 */
@Slf4j
@RestController
@RequestMapping("/web/socket/stomp")
@RequiredArgsConstructor
public class WebSocketStompController {

    private final RabbitTemplate rabbitTemplate;

    private final RedisSimpleUtil redisSimpleUtil;

    @MessageExceptionHandler(Exception.class)
    @SendToUser("/queue/errors")
    public Exception handleExceptions(Exception t) {
        t.printStackTrace();
        return t;
    }


    @ResponseBody
    @PostMapping("/pushMessage")
    public ResponseWrapper sendMessage(@RequestBody WebSocketMsgVO message) {
        try {
            this.rabbitTemplate.convertAndSend(RabbitMqConfig.SOCKET_MSG_EXCHANGE, null, JSONUtil.toJsonStr(message));
            return ResponseWrapper.ok();
        } catch (Exception e) {
            return ResponseWrapper.error(1000,"发送失败"+e.getMessage());
        }
    }

}
